package com.atguigu.daijia.common.login;

import com.atguigu.daijia.common.constant.RedisConstant;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.common.util.AuthContextHolder;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.concurrent.TimeUnit;

/*
* 切面类
* */
@Component
@Aspect //标志切面类
public class GuiguLoginAspect {

    @Autowired
    private RedisTemplate redisTemplate;

    /*
    * 登录校验
    * 用环绕通知
    *
    * proceedingJoinPoint.proceed() 执行业务方法
    * */
    @Around("execution(* com.atguigu.daijia.*.controller.*.*(..)) && @annotation(GuiguLogin)")
    public Object login(ProceedingJoinPoint proceedingJoinPoint, GuiguLogin GuiguLogin) throws Throwable {

        //获取request 从请求头获得token
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();//spring提供的工具
        HttpServletRequest request = sra.getRequest();//拿到请求头
        String token = request.getHeader("token");

        //如果没有token，则不通过登录
        if(!StringUtils.hasText(token)){
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }

        //通过token去redis查询
        String customerId = (String) redisTemplate.opsForValue().get(RedisConstant.USER_LOGIN_KEY_PREFIX + token);

        //如果没有查询到，则不通过
        if(!StringUtils.hasText(customerId)){
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }
        //刷新登录过期时间
        redisTemplate.opsForValue().set(RedisConstant.USER_LOGIN_KEY_PREFIX + token,customerId,
                RedisConstant.USER_LOGIN_KEY_TIMEOUT, TimeUnit.HOURS);

        //把id放到threadlocal中（跟当前线程绑定的对象，后面可以直接从threadlocal中拿）
        AuthContextHolder.setUserId(Long.parseLong(customerId));

        //执行业务方法
        return proceedingJoinPoint.proceed();
    }

}
